<?php

namespace App\Jobs;

use App\Models\User\Invoice;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Log;
use Mail;

class SendInvoiceEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $id;
    public $email;
    public $file_path;

    public function __construct($id, $email, $file_path)
    {
        $this->id        = $id;
        $this->email     = $email;
        $this->file_path = $file_path;
    }

    public function handle()
    {
        $user_email = $this->email;
        $file_path  = $this->file_path;
    //    var_dump($user_email,$file_path);
//        //模板发送
        try{
            Mail::send('public.email.invoice_email', [
                'username'  => '尊敬的会员',
                'site_name' => config('base.email.MAIL_FROM_NAME', config('base.base.site_name')),
            ],
                function ($message) use ($user_email, $file_path) {
                    $to = $user_email;
                    $message->to($to)->subject('电子发票');
                    //在邮件中上传附件
                    //	$file_path='/storage/upload/invoice/FbF1d5V9QIWcNV7cObl1U9MAXNDwHXp7pA1Y2ZAq.png';
                    $attachment = public_path($file_path);
                    $message->attach($attachment, ['as' => now().'_invoice.jpg']);


//					$message->attach($attachment,['as'=>'invoice.jpg']);
//					$message->attach($attachment);
                });
            if (count(Mail::failures()) < 1) {
                $invoice =  Invoice::where('id',$this->id)->first();
                $invoice->email_send_time = now();
                $invoice->save();
            } else {
                Log::channel( 'email' )->error( '发送发票失败'.'invoice_id='.$this->id);
            }

        }catch (\Exception $e){
            var_dump($e->getMessage());
        }

    }
}
